package team.yidong.fenda.serviceImpl;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import net.sf.json.JsonConfig;
import org.codehaus.groovy.transform.trait.Traits;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import team.yidong.fenda.DTO.SysUserPermissionDTO;
import team.yidong.fenda.entity.*;
import team.yidong.fenda.repository.*;
import team.yidong.fenda.service.HospitalService;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import java.util.ArrayList;
import java.util.List;


@Service
public class HospitalServiceImpl implements HospitalService {
    @Autowired
    HospitalRepository hospitalRepository;
    @Autowired
    MasterRepository masterRepository;
    @Autowired
    SysUserRepository sysUserRepository;
    @Autowired
    HospitalDepartmentRepository hospitalDepartmentRepository;
    @Autowired
    SysUserRoleRepository sysUserRoleRepository;
    @Autowired
    SysUserPermissionRepository sysUserPermissionRepository;
    @Autowired
    SysRolePermissionRepository sysRolePermissionRepository;

    @Override
    public JSONObject findHospitalCriteria(Integer id, String hospitalName, Double proportion, String tixianTime, Integer page, Integer page_size) {
        Pageable pageable = new PageRequest(page, page_size);
        Page<Hospital> hospitalPage = hospitalRepository.findAll(new Specification<Hospital>() {
            @Override
            public Predicate toPredicate(Root<Hospital> root, CriteriaQuery<?> criteriaQuery, CriteriaBuilder criteriaBuilder) {

                //用list来保存条件列表
                List<Predicate> preList = new ArrayList<Predicate>();
                //单个查询
                if (id != 1) {
                    Predicate p1 = criteriaBuilder.equal(root.get("id").as(Integer.class), id);
                    preList.add(p1);
                } else {
                    Predicate p1 = criteriaBuilder.notEqual(root.get("id").as(Integer.class), id);
                    preList.add(p1);
                }
                if (hospitalName != null && !hospitalName.equals("")) {
                    Predicate p = criteriaBuilder.like(root.get("name").as(String.class), "%" + hospitalName + "%");
                    preList.add(p);
                }
                if (proportion != null && !proportion.equals("")) {
                    Predicate p = criteriaBuilder.equal(root.get("proportion").as(Double.class), proportion);
                    preList.add(p);
                }
                if (tixianTime != null && !tixianTime.equals("")) {
                    Predicate p = criteriaBuilder.equal(root.get("tixianTime").as(Integer.class), tixianTime);
                    preList.add(p);
                }
                criteriaQuery.where(preList.toArray(new Predicate[preList.size()]));
                return null;
            }
        }, pageable);

        JsonConfig config = new JsonConfig();
        config.setExcludes(new String[]{"hospital", "hospitalPermissionSet", "userSet", "masterList"});
        JSONObject jsonObject = JSONObject.fromObject(hospitalPage, config);
        String temp = "{\"total\":" + jsonObject.getString("totalElements") + ",\"rows\":" + jsonObject.getString("content") + "}";
        JSONObject j = JSONObject.fromObject(temp);
        return j;
    }

    @Override
    public Hospital findHospitalById(Integer id) {
        return hospitalRepository.findOne(id);
    }

    @Override
    public Hospital findByName(String hospitalName) {
        return hospitalRepository.findByName(hospitalName);
    }

    @Transactional
    @Override
    public String saveHospital(String hospitalName, Double proportion, String userName, String password, String departmentName, String tixianTime, String jgxxgl, String tp, String bmgl, String jgflgl, String jgjjgl, String zjxxgl, String zjdtmx, String yyslgl, String xxgl, String lscx, String wtgl, String hmd, String dd, String yhhhgl, String ztjz) {
        if (sysUserRepository.findByUserName(userName) != null) {
            return "用户名已存在，请重新输入";
        } else {
            Hospital hospital = new Hospital();
            hospital.setName(hospitalName);
            hospital.setTixianTime(Integer.parseInt(tixianTime));
            hospital.setProportion(proportion);
            hospitalRepository.save(hospital);
            HospitalDepartment hospitalDepartment = new HospitalDepartment();
            hospitalDepartment.setDepartmentName(departmentName);
            hospitalDepartment.setHospitalId(hospital.getId());
            hospitalDepartmentRepository.save(hospitalDepartment);
            SysUserRole sysUserRole = new SysUserRole();
            sysUserRole.setInfo("hospitalAdmin");
            sysUserRoleRepository.save(sysUserRole);
            SysUser sysUser = new SysUser();
            sysUser.setHospitalId(hospital.getId());
            sysUser.setUserName(userName);
            sysUser.setPassword(password);
            sysUser.setSysUserRoleId(sysUserRole.getId());
            sysUserRepository.save(sysUser);

            if (jgxxgl != null && !jgxxgl.equals("")) {
                SysRolePermission sysRolePermission = new SysRolePermission();
                sysRolePermission.setRoleId(sysUserRole.getId());
                SysUserPermission sysUserPermission = sysUserPermissionRepository.findByPermission("jgxxgl");
                sysRolePermission.setPermissionId(sysUserPermission.getId());
                sysRolePermissionRepository.save(sysRolePermission);

                SysRolePermission sysRolePermission1 = new SysRolePermission();
                sysRolePermission.setRoleId(sysUserRole.getId());
                SysUserPermission sysUserPermission1 = sysUserPermissionRepository.findByPermission("jggl");
                sysRolePermission.setPermissionId(sysUserPermission1.getId());
                sysRolePermissionRepository.save(sysRolePermission1);
            }
            if (tp != null && !tp.equals("")) {
                SysRolePermission sysRolePermission = new SysRolePermission();
                sysRolePermission.setRoleId(sysUserRole.getId());
                SysUserPermission sysUserPermission = sysUserPermissionRepository.findByPermission("tp");
                sysRolePermission.setPermissionId(sysUserPermission.getId());
                sysRolePermissionRepository.save(sysRolePermission);

                SysRolePermission sysRolePermission1 = new SysRolePermission();
                sysRolePermission.setRoleId(sysUserRole.getId());
                SysUserPermission sysUserPermission1 = sysUserPermissionRepository.findByPermission("jggl");
                sysRolePermission.setPermissionId(sysUserPermission1.getId());
                sysRolePermissionRepository.save(sysRolePermission1);
            }
            if (bmgl != null && !bmgl.equals("")) {
                SysRolePermission sysRolePermission = new SysRolePermission();
                sysRolePermission.setRoleId(sysUserRole.getId());
                SysUserPermission sysUserPermission = sysUserPermissionRepository.findByPermission("bmgl");
                sysRolePermission.setPermissionId(sysUserPermission.getId());
                sysRolePermissionRepository.save(sysRolePermission);

                SysRolePermission sysRolePermission1 = new SysRolePermission();
                sysRolePermission.setRoleId(sysUserRole.getId());
                SysUserPermission sysUserPermission1 = sysUserPermissionRepository.findByPermission("jggl");
                sysRolePermission.setPermissionId(sysUserPermission1.getId());
                sysRolePermissionRepository.save(sysRolePermission1);
            }
            if (jgflgl != null && !jgflgl.equals("")) {
                SysRolePermission sysRolePermission = new SysRolePermission();
                sysRolePermission.setRoleId(sysUserRole.getId());
                SysUserPermission sysUserPermission = sysUserPermissionRepository.findByPermission("jgflgl");
                sysRolePermission.setPermissionId(sysUserPermission.getId());
                sysRolePermissionRepository.save(sysRolePermission);

                SysRolePermission sysRolePermission1 = new SysRolePermission();
                sysRolePermission.setRoleId(sysUserRole.getId());
                SysUserPermission sysUserPermission1 = sysUserPermissionRepository.findByPermission("jggl");
                sysRolePermission.setPermissionId(sysUserPermission1.getId());
                sysRolePermissionRepository.save(sysRolePermission1);
            }
            if (jgjjgl != null && !jgjjgl.equals("")) {
                SysRolePermission sysRolePermission = new SysRolePermission();
                sysRolePermission.setRoleId(sysUserRole.getId());
                SysUserPermission sysUserPermission = sysUserPermissionRepository.findByPermission("jgjjgl");
                sysRolePermission.setPermissionId(sysUserPermission.getId());
                sysRolePermissionRepository.save(sysRolePermission);

                SysRolePermission sysRolePermission1 = new SysRolePermission();
                sysRolePermission.setRoleId(sysUserRole.getId());
                SysUserPermission sysUserPermission1 = sysUserPermissionRepository.findByPermission("jggl");
                sysRolePermission.setPermissionId(sysUserPermission1.getId());
                sysRolePermissionRepository.save(sysRolePermission1);
            }
            if (zjxxgl != null && !zjxxgl.equals("")) {
                SysRolePermission sysRolePermission = new SysRolePermission();
                sysRolePermission.setRoleId(sysUserRole.getId());
                SysUserPermission sysUserPermission = sysUserPermissionRepository.findByPermission("zjxxgl");
                sysRolePermission.setPermissionId(sysUserPermission.getId());
                sysRolePermissionRepository.save(sysRolePermission);

                SysRolePermission sysRolePermission1 = new SysRolePermission();
                sysRolePermission.setRoleId(sysUserRole.getId());
                SysUserPermission sysUserPermission1 = sysUserPermissionRepository.findByPermission("zjgl");
                sysRolePermission.setPermissionId(sysUserPermission1.getId());
                sysRolePermissionRepository.save(sysRolePermission1);
            }
            if (zjdtmx != null && !zjdtmx.equals("")) {
                SysRolePermission sysRolePermission = new SysRolePermission();
                sysRolePermission.setRoleId(sysUserRole.getId());
                SysUserPermission sysUserPermission = sysUserPermissionRepository.findByPermission("zjdtmx");
                sysRolePermission.setPermissionId(sysUserPermission.getId());
                sysRolePermissionRepository.save(sysRolePermission);

                SysRolePermission sysRolePermission1 = new SysRolePermission();
                sysRolePermission.setRoleId(sysUserRole.getId());
                SysUserPermission sysUserPermission1 = sysUserPermissionRepository.findByPermission("jggl");
                sysRolePermission.setPermissionId(sysUserPermission1.getId());
                sysRolePermissionRepository.save(sysRolePermission1);
            }
            if (yyslgl != null && !yyslgl.equals("")) {
                SysRolePermission sysRolePermission = new SysRolePermission();
                sysRolePermission.setRoleId(sysUserRole.getId());
                SysUserPermission sysUserPermission = sysUserPermissionRepository.findByPermission("yyslgl");
                sysRolePermission.setPermissionId(sysUserPermission.getId());
                sysRolePermissionRepository.save(sysRolePermission);

                SysRolePermission sysRolePermission1 = new SysRolePermission();
                sysRolePermission.setRoleId(sysUserRole.getId());
                SysUserPermission sysUserPermission1 = sysUserPermissionRepository.findByPermission("yygl");
                sysRolePermission.setPermissionId(sysUserPermission1.getId());
                sysRolePermissionRepository.save(sysRolePermission1);
            }
            if (xxgl != null && !xxgl.equals("")) {
                SysRolePermission sysRolePermission = new SysRolePermission();
                sysRolePermission.setRoleId(sysUserRole.getId());
                SysUserPermission sysUserPermission = sysUserPermissionRepository.findByPermission("xxgl");
                sysRolePermission.setPermissionId(sysUserPermission.getId());
                sysRolePermissionRepository.save(sysRolePermission);
                SysRolePermission sysRolePermission1 = new SysRolePermission();
                sysRolePermission.setRoleId(sysUserRole.getId());
                SysUserPermission sysUserPermission1 = sysUserPermissionRepository.findByPermission("yygl");
                sysRolePermission.setPermissionId(sysUserPermission1.getId());
                sysRolePermissionRepository.save(sysRolePermission1);
            }
            if (lscx != null && !lscx.equals("")) {
                SysRolePermission sysRolePermission = new SysRolePermission();
                sysRolePermission.setRoleId(sysUserRole.getId());
                SysUserPermission sysUserPermission = sysUserPermissionRepository.findByPermission("lscx");
                sysRolePermission.setPermissionId(sysUserPermission.getId());
                sysRolePermissionRepository.save(sysRolePermission);
                SysRolePermission sysRolePermission1 = new SysRolePermission();
                sysRolePermission.setRoleId(sysUserRole.getId());
                SysUserPermission sysUserPermission1 = sysUserPermissionRepository.findByPermission("yygl");
                sysRolePermission.setPermissionId(sysUserPermission1.getId());
                sysRolePermissionRepository.save(sysRolePermission1);
            }
            if (wtgl != null && !wtgl.equals("")) {
                SysRolePermission sysRolePermission = new SysRolePermission();
                sysRolePermission.setRoleId(sysUserRole.getId());
                SysUserPermission sysUserPermission = sysUserPermissionRepository.findByPermission("wtgl");
                sysRolePermission.setPermissionId(sysUserPermission.getId());
                sysRolePermissionRepository.save(sysRolePermission);
            }
            if (hmd != null && !hmd.equals("")) {
                SysRolePermission sysRolePermission = new SysRolePermission();
                sysRolePermission.setRoleId(sysUserRole.getId());
                SysUserPermission sysUserPermission = sysUserPermissionRepository.findByPermission("hmd");
                sysRolePermission.setPermissionId(sysUserPermission.getId());
                sysRolePermissionRepository.save(sysRolePermission);
            }
            if (dd != null && !dd.equals("")) {
                SysRolePermission sysRolePermission = new SysRolePermission();
                sysRolePermission.setRoleId(sysUserRole.getId());
                SysUserPermission sysUserPermission = sysUserPermissionRepository.findByPermission("dd");
                sysRolePermission.setPermissionId(sysUserPermission.getId());
                sysRolePermissionRepository.save(sysRolePermission);
            }
            if (yhhhgl != null && !yhhhgl.equals("")) {
                SysRolePermission sysRolePermission = new SysRolePermission();
                sysRolePermission.setRoleId(sysUserRole.getId());
                SysUserPermission sysUserPermission = sysUserPermissionRepository.findByPermission("yhhhgl");
                sysRolePermission.setPermissionId(sysUserPermission.getId());
                sysRolePermissionRepository.save(sysRolePermission);
            }
            if (ztjz != null && !ztjz.equals("")) {
                SysRolePermission sysRolePermission = new SysRolePermission();
                sysRolePermission.setRoleId(sysUserRole.getId());
                SysUserPermission sysUserPermission = sysUserPermissionRepository.findByPermission("ztjz");
                sysRolePermission.setPermissionId(sysUserPermission.getId());
                sysRolePermissionRepository.save(sysRolePermission);
            }
            Master master = new Master();
            master.setIsBlack("否");
            master.setUserName(userName);
            master.setPassword(password);
            master.setName("白衣天使");
            master.setInfo("白衣天使");
            master.setGoodAt("白衣天使");
            master.setHospital(hospital);
            master.setHeadImg("https://qny.liuxuanlong.xyz/timg%20%283%29.jpg");
            masterRepository.save(master);
            return "添加成功";
        }

    }


    @Override
    public JSONArray findAll() {
        List<Hospital> hospitalList = hospitalRepository.findAll();
        JsonConfig jsonConfig = new JsonConfig();
        jsonConfig.setExcludes(new String[]{"hospital", "hospitalPermissionSet", "userSet", "masterList"});
        return JSONArray.fromObject(hospitalList, jsonConfig);
    }

    @Override
    public List<Hospital> findByImgId(Integer imgId) {
        List<Hospital> hospitalList = hospitalRepository.findAll(new Specification<Hospital>() {
            @Override
            public Predicate toPredicate(Root<Hospital> root, CriteriaQuery<?> criteriaQuery, CriteriaBuilder criteriaBuilder) {
                List<Predicate> preList = new ArrayList<Predicate>();
                Predicate predicate = criteriaBuilder.equal(root.get("hospitalImgSet").get("id"), imgId);
                preList.add(predicate);
                criteriaQuery.where(preList.toArray(new Predicate[preList.size()]));
                return null;
            }
        });
        return hospitalList;
    }


    public void deleteHospital(Iterable<Hospital> hospitalIterable) {
        hospitalRepository.delete(hospitalIterable);
    }


    @Transactional
    @Override
    public void updateProportion(Integer hospitalId, Integer tixianTime) {
        Hospital hospital = hospitalRepository.findOne(hospitalId);
        hospital.setTixianTime(tixianTime);
        hospitalRepository.saveAndFlush(hospital);
    }

    @Override
    public void update(Integer hospitalId, String updateInfo) {
        Hospital hospital = hospitalRepository.findOne(hospitalId);

    }

    @Override
    public String findHospitalNameById(Integer hospitalId) {
        return hospitalRepository.findOne(hospitalId).getName();
    }

    @Override
    public JSONArray findSysUserPermission(Integer userId) {
        List<String> permissionList = new ArrayList<>();
        List<SysRolePermission> sysRolePermissionList = sysRolePermissionRepository.findByRoleId(sysUserRepository.findOne(userId).getSysUserRoleId());
        for (SysRolePermission sysRolePermission : sysRolePermissionList) {
            SysUserPermission sysUserPermission = sysUserPermissionRepository.findByIdAndResourceType(sysRolePermission.getPermissionId(), "page");
            if (sysUserPermission != null) {
                permissionList.add(sysUserPermission.getPermission());
            }

        }
        return JSONArray.fromObject(permissionList);
    }

    @Override
    public JSONArray findAllSysUser() {

        return JSONArray.fromObject(sysUserRepository.findAll());
    }

    @Override
    public JSONArray findAllSysUserPermission(String hospitalName, String sysUserName) {
        List<SysUserPermissionDTO> sysUserPermissionDTOList = new ArrayList<>();
        List<SysUser> sysUserList = sysUserRepository.findAll(new Specification<SysUser>() {
            List<Predicate> predicateList = new ArrayList<>();

            @Override
            public Predicate toPredicate(Root<SysUser> root, CriteriaQuery<?> criteriaQuery, CriteriaBuilder criteriaBuilder) {
                if (hospitalName != null && !hospitalName.equals("")) {
                    Hospital hospital = hospitalRepository.findByName(hospitalName);
                    Predicate p = criteriaBuilder.equal(root.get("hospitalId"), hospital.getId());
                    predicateList.add(p);
                }
                if (sysUserName != null && !sysUserName.equals("")) {
                    Predicate p = criteriaBuilder.like(root.get("userName"), "%" + sysUserName + "%");
                    predicateList.add(p);
                }
                Predicate predicate = criteriaBuilder.notEqual(root.get("sysUserRoleId").as(Integer.class), 1);
                Predicate predicate1 = criteriaBuilder.notEqual(root.get("sysUserRoleId").as(Integer.class), 3);
                predicateList.add(predicate1);
                predicateList.add(predicate);
                criteriaQuery.where(predicateList.toArray(new Predicate[predicateList.size()]));
                return null;
            }
        });
        for (SysUser sysUser : sysUserList) {
            List<SysRolePermission> sysRolePermissionList = sysRolePermissionRepository.findByRoleId(sysUser.getSysUserRoleId());
            for (SysRolePermission sysRolePermission : sysRolePermissionList) {
                SysUserPermission sysUserPermission = sysUserPermissionRepository.findByIdAndResourceType(sysRolePermission.getPermissionId(), "page");
                if (sysUserPermission != null) {
                    SysUserPermissionDTO sysUserPermissionDTO = new SysUserPermissionDTO();
                    sysUserPermissionDTO.setRoleId(sysRolePermission.getRoleId());
                    sysUserPermissionDTO.setUserId(sysUser.getId());
                    sysUserPermissionDTO.setPermissionId(sysUserPermission.getId());
                    sysUserPermissionDTO.setPermissionName(sysUserPermission.getName());
                    sysUserPermissionDTO.setSysUserName(sysUser.getUserName());
                    sysUserPermissionDTO.setHospitalId(sysUser.getHospitalId());
                    sysUserPermissionDTO.setHospitalName(hospitalRepository.findOne(sysUser.getHospitalId()).getName());
                    sysUserPermissionDTOList.add(sysUserPermissionDTO);
                }

            }
        }
        return JSONArray.fromObject(sysUserPermissionDTOList);
    }

    @Override
    public JSONArray findAllHospitalAdmin() {
        List<SysUser> sysUserList = sysUserRepository.findHospitalAdmin();
        return JSONArray.fromObject(sysUserList);
    }

    @Override
    public JSONArray findUserRestPermission(Integer userId) {
        //用户已有的权限
        SysUser sysUser = sysUserRepository.findOne(userId);
        List<SysUserPermission> sysUserPermissionList = new ArrayList<>();
        List<SysRolePermission> sysRolePermissionList = sysRolePermissionRepository.findByRoleId(sysUser.getSysUserRoleId());
        for (SysRolePermission sysRolePermission : sysRolePermissionList) {
            SysUserPermission sysUserPermission = sysUserPermissionRepository.findByIdAndResourceType(sysRolePermission.getPermissionId(), "page");
            if (sysUserPermission != null) {
                sysUserPermissionList.add(sysUserPermission);
            }
        }

        //查询没有的权限
        if (sysUserPermissionList == null || sysUserPermissionList.size() == 0) {
            return JSONArray.fromObject(sysUserPermissionRepository.findByResourceType("page"));
        } else {
            List<SysUserPermission> sysUserPermissionList1 = sysUserPermissionRepository.findRestPermission(sysUserPermissionList, "page");
            return JSONArray.fromObject(sysUserPermissionList1);
        }

    }

    @Transactional
    @Override
    public void addSysUserPermission(Integer userId, Integer permissionId) {
        SysUser sysUser = sysUserRepository.findOne(userId);
        SysRolePermission sysRolePermission = new SysRolePermission();
        sysRolePermission.setPermissionId(permissionId);
        sysRolePermission.setRoleId(sysUser.getSysUserRoleId());
        sysRolePermissionRepository.save(sysRolePermission);
        if (permissionId == 1 || permissionId == 2 || permissionId == 12 || permissionId == 16 || permissionId == 17) {
            SysRolePermission sysRolePermission1 = new SysRolePermission();
            sysRolePermission1.setPermissionId(9);
            sysRolePermission1.setRoleId(sysUser.getSysUserRoleId());
            sysRolePermissionRepository.save(sysRolePermission1);
        }
        if (permissionId==18||permissionId==19){
            SysRolePermission sysRolePermission1 = new SysRolePermission();
            sysRolePermission1.setPermissionId(10);
            sysRolePermission1.setRoleId(sysUser.getSysUserRoleId());
            sysRolePermissionRepository.save(sysRolePermission1);
        }
        if (permissionId==20||permissionId==21||permissionId==22){
            SysRolePermission sysRolePermission1 = new SysRolePermission();
            sysRolePermission1.setPermissionId(15);
            sysRolePermission1.setRoleId(sysUser.getSysUserRoleId());
            sysRolePermissionRepository.save(sysRolePermission1);
        }

    }

    @Transactional
    @Override
    public void deleteSysUserPermission(Integer roleId, Integer permissionId) {
        System.out.println(roleId + "******" + permissionId);
        SysRolePermission sysRolePermission = sysRolePermissionRepository.findByPermissionIdAndRoleId(permissionId, roleId);
        System.out.println(sysRolePermission.getId());
        sysRolePermissionRepository.delete(sysRolePermission);
    }


}
